const { app, BrowserWindow, ipcMain, screen } = require("electron");
const path = require("path");
const sharp = require("sharp");
const fs = require("fs");
const mdns = require("multicast-dns")();

let fileList = [];
let mainWindow;
let fileIndex = 3;

function createWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  mainWindow = new BrowserWindow({
    width,
    height,
    frame: false,
    fullscreen: true,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });
  mainWindow.webContents.openDevTools();
  mainWindow.webContents.on("did-finish-load", () => {
    mainWindow.webContents.send("update", fileList.length);
  });
  mainWindow.loadFile("./assets/web/index.html");
}
async function buildCache() {
  const inputDir = "./store/imgs";
  const outputDir = "./cache";
  fileList = fs.readdirSync(inputDir);
  const promises = [];
  for (let i = 0; i < 3 && i < fileList.length; i++) {
    const filePath = path.join(inputDir, fileList[i]);
    promises.push(convertToAVIF(filePath, outputDir, String(i)));
  }
  await Promise.all(promises);
}
function listenMDNS() {
  mdns.on("query", (query) => {
    // 检查是否为针对 _electron._tcp.local 的查询
    if (
      query.questions.some((q) => q.name === "_electronic_album._tcp.local")
    ) {
      mdns.response({
        answers: [
          {
            name: "_electronic_album._tcp.local",
            type: "PTR",
            data: "_electronic_album._electron._tcp.local",
            ttl: 120,
          },
          {
            name: "_electronic_album._electron._tcp.local",
            type: "SRV",
            data: { port: 8080, target: "_electronic_album.local" }, // 替换为实际端口
            ttl: 120,
          },
          {
            name: "_electronic_album.local",
            type: "A",
            data: require("os").networkInterfaces().eth0[0].address,
            ttl: 120,
          },
        ],
      });
    }
  });
}
app.whenReady().then(async () => {
  await buildCache();
  ipcMain.handle("getNewImage", updateCache);
  createWindow();
  listenMDNS();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

/**
 *
 * @param {string} inputPath
 * @param {string} outputDir
 * @param {string} name
 */
async function convertToAVIF(inputPath, outputDir, name) {
  const outputPath = path.join(outputDir, `${name}.avif`);
  await sharp(inputPath)
    .toFormat("avif", {
      quality: 100, // 质量（0-100）
      lossless: true, // 是否无损压缩
    })
    .toFile(outputPath);
}
function updateStore(size) {
  mainWindow.webContents.send("update", size);
}
async function updateCache(name) {
  await sharp(path.join("./store/imgs", fileList[fileIndex++]))
    .toFormat("avif", {
      quality: 100, // 质量（0-100）
      lossless: true, // 是否无损压缩
    })
    .toFile(path.join("./cache/", name));
  if (fileIndex === fileList.length) fileIndex = 0;
  return name;
}
